﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.DataType;

namespace 表单批量填写器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "form_filler_browser";
        private const string FORM_URL = "https://httpbin.org/forms/post";
        
        private List<FormDataModel> _formDataList = new List<FormDataModel>();
        private int _currentIndex = 0;
        private bool _isBrowserReady = false;

        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
            this.FormClosing += Form1_FormClosing;
        }

        #region 初始化和清理

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateBrowser();
            UpdateUIState();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseBrowser();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        #endregion

        #region 浏览器操作

        /// <summary>
        /// 创建嵌入式浏览器
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 配置窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // 嵌入到 Panel 中
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "表单填写浏览器"
                };

                // 浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    FORM_URL,
                    windowInfo,
                    settings,
                    null,
                    null,
                    browserEvent,
                    default,
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    UpdateStatus("正在创建浏览器...");
                }
                else
                {
                    MessageBox.Show("浏览器创建失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 关闭浏览器
        /// </summary>
        private void CloseBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(true, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导航到指定 URL
        /// </summary>
        private void NavigateToUrl(string url)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null)
                    {
                        frame.LoadURL(url);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Excel 导入

        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog dialog = new OpenFileDialog())
                {
                    dialog.Filter = "Excel 文件|*.xlsx;*.xls|CSV 文件|*.csv|所有文件|*.*";
                    dialog.Title = "选择要导入的数据文件";

                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        ImportExcelData(dialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ImportExcelData(string filePath)
        {
            try
            {
                // 导入数据
                _formDataList = ExcelHelper.ImportFromExcel(filePath);

                if (_formDataList.Count == 0)
                {
                    MessageBox.Show("没有找到有效的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 显示在列表框中
                listBoxData.Items.Clear();
                foreach (var data in _formDataList)
                {
                    listBoxData.Items.Add(data.ToString());
                }

                _currentIndex = 0;
                UpdateStatus($"成功导入 {_formDataList.Count} 条数据");
                UpdateUIState();

                MessageBox.Show($"成功导入 {_formDataList.Count} 条数据！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入数据失败: {ex.Message}\n\n提示：请确保安装了 Microsoft Access Database Engine。", 
                    "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCreateTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                using (SaveFileDialog dialog = new SaveFileDialog())
                {
                    dialog.Filter = "CSV 文件|*.csv";
                    dialog.Title = "保存模板文件";
                    dialog.FileName = "表单数据模板.csv";

                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        ExcelHelper.CreateExcelTemplate(dialog.FileName);
                        MessageBox.Show($"模板文件已创建：{dialog.FileName}\n\n请使用 Excel 打开并填写数据。", 
                            "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建模板失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 表单填写

        private void btnFillCurrent_Click(object sender, EventArgs e)
        {
            if (!ValidateFillOperation())
                return;

            FillForm(_formDataList[_currentIndex]);
        }

        private void btnFillAll_Click(object sender, EventArgs e)
        {
            if (!ValidateFillOperation())
                return;

            if (MessageBox.Show($"确定要批量填写 {_formDataList.Count} 条数据吗？\n\n每条数据填写后会自动提交并等待 3 秒。", 
                "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;

            // 开始批量填写
            _currentIndex = 0;
            BatchFillForms();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (_formDataList.Count == 0)
                return;

            _currentIndex++;
            if (_currentIndex >= _formDataList.Count)
                _currentIndex = 0;

            listBoxData.SelectedIndex = _currentIndex;
            UpdateUIState();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (_formDataList.Count == 0)
                return;

            _currentIndex--;
            if (_currentIndex < 0)
                _currentIndex = _formDataList.Count - 1;

            listBoxData.SelectedIndex = _currentIndex;
            UpdateUIState();
        }

        private bool ValidateFillOperation()
        {
            if (_formDataList.Count == 0)
            {
                MessageBox.Show("请先导入数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            if (!_isBrowserReady)
            {
                MessageBox.Show("浏览器尚未就绪，请等待页面加载完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 填写单个表单
        /// </summary>
        private void FillForm(FormDataModel data)
        {
            try
            {
                UpdateStatus($"正在填写: {data.CustomerName}...");

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var frame = browser.GetMainFrame();
                if (frame == null)
                {
                    MessageBox.Show("无法获取浏览器框架！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 构建 JavaScript 填写脚本
                string script = GenerateFillScript(data);

                // 执行脚本
                frame.ExecuteJavaScript(script, "", 0);

                UpdateStatus($"已填写: {data.CustomerName}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"填写表单失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 批量填写表单
        /// </summary>
        private void BatchFillForms()
        {
            if (_currentIndex >= _formDataList.Count)
            {
                MessageBox.Show($"批量填写完成！共填写 {_formDataList.Count} 条数据。", 
                    "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _currentIndex = 0;
                return;
            }

            // 填写当前表单
            var data = _formDataList[_currentIndex];
            FillForm(data);

            // 提交表单
            SubmitForm();

            // 更新进度
            listBoxData.SelectedIndex = _currentIndex;
            UpdateStatus($"进度: {_currentIndex + 1}/{_formDataList.Count}");

            // 等待 3 秒后继续下一条
            _currentIndex++;
            
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 3000;
            timer.Tick += (s, e) =>
            {
                timer.Stop();
                timer.Dispose();
                
                // 重新加载页面
                NavigateToUrl(FORM_URL);
                
                // 等待页面加载后继续
                System.Windows.Forms.Timer loadTimer = new System.Windows.Forms.Timer();
                loadTimer.Interval = 2000;
                loadTimer.Tick += (s2, e2) =>
                {
                    loadTimer.Stop();
                    loadTimer.Dispose();
                    BatchFillForms();
                };
                loadTimer.Start();
            };
            timer.Start();
        }

        /// <summary>
        /// 生成表单填写 JavaScript 脚本
        /// </summary>
        private string GenerateFillScript(FormDataModel data)
        {
            var script = @"
(function() {
    try {
        // 填写客户姓名
        var custname = document.querySelector('input[name=""custname""]');
        if (custname) custname.value = '" + EscapeJsString(data.CustomerName) + @"';
        
        // 填写电话
        var custtel = document.querySelector('input[name=""custtel""]');
        if (custtel) custtel.value = '" + EscapeJsString(data.Telephone) + @"';
        
        // 填写邮箱
        var custemail = document.querySelector('input[name=""custemail""]');
        if (custemail) custemail.value = '" + EscapeJsString(data.Email) + @"';
        
        // 选择披萨尺寸
        if ('" + data.PizzaSize + @"') {
            var sizeRadio = document.querySelector('input[name=""size""][value=""" + data.PizzaSize.ToLower() + @"""]');
            if (sizeRadio) sizeRadio.checked = true;
        }
        
        // 选择配料（先取消所有选择）
        var toppingCheckboxes = document.querySelectorAll('input[name=""topping""]');
        toppingCheckboxes.forEach(function(cb) { cb.checked = false; });
        
        // 选择指定的配料
        var toppings = '" + data.PizzaToppings + @"'.toLowerCase().split(/[,;|]/);
        toppings.forEach(function(topping) {
            topping = topping.trim();
            if (topping) {
                var cb = document.querySelector('input[name=""topping""][value=""' + topping + '""]');
                if (cb) cb.checked = true;
            }
        });
        
        // 填写配送时间
        var delivery = document.querySelector('input[name=""delivery""]');
        if (delivery) delivery.value = '" + EscapeJsString(data.DeliveryTime) + @"';
        
        // 填写备注
        var comments = document.querySelector('textarea[name=""comments""]');
        if (comments) comments.value = '" + EscapeJsString(data.Comments) + @"';
        
        console.log('✅ 表单填写成功');
    } catch (e) {
        console.error('❌ 表单填写失败:', e);
    }
})();
";
            return script;
        }

        /// <summary>
        /// 提交表单
        /// </summary>
        private void SubmitForm()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null)
                    {
                        string script = @"
(function() {
    var submitBtn = document.querySelector('button[type=""submit""]') || 
                    document.querySelector('input[type=""submit""]');
    if (submitBtn) {
        submitBtn.click();
        console.log('✅ 表单已提交');
    }
})();
";
                        frame.ExecuteJavaScript(script, "", 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"提交表单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 转义 JavaScript 字符串
        /// </summary>
        private string EscapeJsString(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";

            return str.Replace("\\", "\\\\")
                      .Replace("'", "\\'")
                      .Replace("\"", "\\\"")
                      .Replace("\n", "\\n")
                      .Replace("\r", "\\r");
        }

        #endregion

        #region UI 更新（从事件线程调用）

        /// <summary>
        /// 更新状态栏（线程安全）
        /// </summary>
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }

            lblStatus.Text = message;
            statusStrip.Refresh();
        }

        /// <summary>
        /// 更新地址栏（线程安全）
        /// </summary>
        public void UpdateUrlTextBox(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrlTextBox(url)));
                return;
            }

            txtUrl.Text = url;
        }

        /// <summary>
        /// 更新标题（线程安全）
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            this.Text = $"表单批量填写器 - {title}";
        }

        /// <summary>
        /// 更新导航按钮状态（线程安全）
        /// </summary>
        public void UpdateNavigationButtons(bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateNavigationButtons(canGoBack, canGoForward)));
                return;
            }

            btnBack.Enabled = canGoBack;
            btnForward.Enabled = canGoForward;
        }

        /// <summary>
        /// 页面加载完成回调
        /// </summary>
        public void OnPageLoadCompleted()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(OnPageLoadCompleted));
                return;
            }

            _isBrowserReady = true;
            UpdateUIState();
        }

        /// <summary>
        /// 更新 UI 状态
        /// </summary>
        private void UpdateUIState()
        {
            bool hasData = _formDataList.Count > 0;
            
            btnFillCurrent.Enabled = hasData && _isBrowserReady;
            btnFillAll.Enabled = hasData && _isBrowserReady;
            btnNext.Enabled = hasData;
            btnPrevious.Enabled = hasData;
            
            if (hasData)
            {
                lblDataCount.Text = $"数据: {_currentIndex + 1}/{_formDataList.Count}";
            }
            else
            {
                lblDataCount.Text = "数据: 0/0";
            }
        }

        #endregion

        #region 导航按钮

        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoBack();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"后退失败: {ex.Message}");
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoForward();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"前进失败: {ex.Message}");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.Reload();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新失败: {ex.Message}");
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        private void txtUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                NavigateToUrl(txtUrl.Text);
                e.Handled = true;
            }
        }

        #endregion
    }
}
